package com.hymjweb.demo.framework.download;

import com.hymjweb.demo.framework.sys.BaseController;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 下载控制器
 * @BelongsProject: demo
 * @BelongsPackage: com.hymjweb.demo.framework.download
 * @Author: luoge
 * @CreateTime: 2020-09-29 22:59
 * @Description:
 */
@Controller
@RequestMapping("/download")
public class DownloadController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(DownloadController.class);

    /** 生成的excel文件扩展名 */
    private static final String FileExt = "xls";

    //https://www.cnblogs.com/kelelipeng/p/11381959.html
    @Value("${my.tempFilePath}")
    private String tempFilePath;


    @Autowired
    private DownloadService downloadService;




    @RequestMapping(value = "/createExcel")
    @ResponseBody
    public Object createExcel(@RequestParam(required = true) Map param,HttpServletResponse response){

        // 获取参数
        // grid的url
        String url= DataTypeUtil.toNotNullString(param.get("sys_url"));
        // 下载的文件名
        String fileName=DataTypeUtil.toNotNullString(param.get("sys_fileName")) + "." + FileExt;
        // 生成的id
        String id=DataTypeUtil.toNotNullString(param.get("_id"));

        // grid表格的表头及字典转换信息
        List<DownloadBean> downloadBeans=downloadService.columnDataConvertToJavaObjct(param.get("columnList"));

        Map<String,String> resultMap=new HashMap<>();

        String miniUiGridDataJsonStr = null;
        File excelFile = null;
        if (!DataTypeUtil.isEmptyStr(url)) {
            // grid分页参数
            String params = DataTypeUtil.toNotNullString(param.get("sys_params"));
            try {
                miniUiGridDataJsonStr = downloadService.sendRequest(url, params);
                // 把查询到的json数据转为File
                excelFile = downloadService.createExcel(tempFilePath,fileName, miniUiGridDataJsonStr, downloadBeans);


                resultMap.put("ok","true");
                resultMap.put("message",this.getLoginUserId());

            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
                resultMap.put("ok","false");
                resultMap.put("message","文件下载失败");
            }
        } else {
            resultMap.put("ok","false");
            resultMap.put("message","文件下载路径不存在");
        }


        return resultMap;
    }


    public void checkDownloadStatus(){
        setRequestAttribute("downloadStatus","ok");
    }


    @RequestMapping(value = "/exportExcel")
    public void exportExcel(String czyId,String fileName, HttpServletResponse response){

        try{

            String downLoadFileName = tempFilePath + czyId + fileName + "." + FileExt;

            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + FileExt, "utf-8"));

            File file=new File(downLoadFileName);
            InputStream in = new FileInputStream(file);
            int count =0;
            byte[] by = new byte[1024];
            //通过response对象获取OutputStream流
            OutputStream out=  response.getOutputStream();
            while((count=in.read(by))!=-1){
                out.write(by, 0, count);//将缓冲区的数据输出到浏览器
            }
            in.close();
            out.flush();
            out.close();
            // 删除已经下载的文件
            file.delete();

        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }


}
